/**
 * 对公众平台发送给公众账号的消息加解密示例代码.
 * 
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

// ------------------------------------------------------------------------

package com.nzw.common.service.wx.aes;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * XMLParse class
 *
 * 提供提取消息格式中的密文及生成回复消息格式的接口.
 */
public class XMLParse {

	/**
	 * 提取出xml数据包中的加密消息
	 * @param xmltext 待提取的xml字符串
	 * @return 提取出的加密消息字符串
	 * @throws com.qq.weixin.mp.aes.AesException
	 */
	public static Object[] extract(String xmltext) throws AesException {
		Object[] result = new Object[3];
		try {
			Document document= DocumentHelper.parseText(xmltext);
			Element root= document.getRootElement();

			Element encry=root.element("Encrypt");
			Element appId=root.element("AppId");

			result[0] = 0;
			result[1] = encry.getText();
			result[2] = appId.getText();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new AesException(AesException.ParseXmlError);
		}
	}

	public static Element getRootElement(String xml){
		if (StringUtils.isEmpty(xml))
			return null;
		Document document= null;
		try {
			document = DocumentHelper.parseText(xml);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		Element root= document.getRootElement();
		return root;
	}

	/**
	 * 生成xml消息
	 * @param encrypt 加密后的消息密文
	 * @param signature 安全签名
	 * @param timestamp 时间戳
	 * @param nonce 随机字符串
	 * @return 生成的xml字符串
	 */
	public static String generate(String encrypt, String signature, String timestamp, String nonce) {

		String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
				+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
				+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
		return String.format(format, encrypt, signature, timestamp, nonce);
	}

	/**
	 * 生成
	 * @param map
	 * @param rootName
	 * @return
	 */
	public static String generateElementAsXml(Map<String,String> map,String rootName){
		Document document= DocumentHelper.createDocument();
		Element root=document.addElement(rootName);
		for (Map.Entry<String,String> entry:map.entrySet()){
			Element ele=root.addElement(entry.getKey());
			ele.setText(entry.getValue());
		}
		return root.asXML();
	}

	/**
	 * xml转map
	 * @param xml
	 * @return
	 */
	public static Map<String,String> xml2Map(String xml){
		Element root=getRootElement(xml);
		Map<String,String> map=new HashMap<>();
		List<Element> elements= root.elements();
		for (Element ele:elements){
			map.put(ele.getName(),ele.getText());
		}
		return map;
	}
}
